package com.donleo.security.jwt.service.impl;

import com.donleo.security.jwt.mapper.ISysUserMapper;
import com.donleo.security.jwt.model.SysPermission;
import com.donleo.security.jwt.model.SysUser;
import com.donleo.security.jwt.service.ISysUserService;
import com.donleo.security.jwt.utils.JwtTokenUtil;
import com.donleo.security.jwt.vo.LoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 * @author liangd
 * date 2020-12-10 14:47
 * code 用户逻辑实现层
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private ISysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public SysUser getUserByName(String name) {
        List<SysUser> users = sysUserMapper.getUserByName(name);
        Assert.isTrue(users.size() == 1, "您输入的账户不存在，或者有多个相同的账户");
        return users.get(0);
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Integer id) {
        return sysUserMapper.getPermissionsByUserId(id);
    }

    @Override
    public String login(LoginParams loginParams) {
        String username = loginParams.getUsername();
        Assert.notNull(username, "账号必须不能为空");
        String password = loginParams.getPassword();
        Assert.notNull(password, "密码必须不能为空");
        SysUser userByName = getUserByName(username);
        //判断用户输入的密码与数据库中查出来的密码是否相等
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        //如果密码相等，表明用户信息输入正确，生成一个token令牌，否则返回null
        if (matches) {
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
        /*
            生成token逻辑：
            根据用户的信息(例如用户名)、token的过期时间和密匙等通过base64加密生成token，
            最后拼接上头部信息，返回jwt token字符串
         */
    }

    @Override
    public Boolean register(SysUser sysUser) {
        String username = sysUser.getUsername();
        Assert.notNull(username, "用户名不能为空");
        String password = sysUser.getPassword();
        Assert.notNull(password, "密码不能为空");
        List<SysUser> user = sysUserMapper.getUserByName(username);
        if (user.size() >= 1) {
            return false;
        }
        sysUser.setPassword(passwordEncoder.encode(password));
        sysUser.setCreateTime(new Date());
        sysUserMapper.insert(sysUser);
        return true;
    }
}
